<template>
  <div class="ai-generate-container">
    <div class="generate-header">
      <a-button type="link" @click="goBack" class="back-btn">
        <ArrowLeftOutlined />
        返回应用市场
      </a-button>
      <h1>AI页面生成器</h1>
      <p v-if="currentApp">基于应用：{{ currentApp.appName }}</p>
    </div>
    
    <div class="generate-content">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-card title="输入需求" class="input-card">
            <a-form layout="vertical">
              <a-form-item label="描述您想要生成的页面内容">
                <a-textarea
                  v-model:value="userMessage"
                  placeholder="请详细描述您想要生成的页面内容，例如：创建一个电商产品展示页面，包含商品列表、筛选功能和购物车..."
                  :rows="8"
                  :maxlength="1000"
                  show-count
                />
              </a-form-item>
              
              <a-form-item label="并行生成数量">
                <a-slider
                  v-model:value="parallelNum"
                  :min="1"
                  :max="10"
                  :marks="{ 1: '1', 5: '5', 10: '10' }"
                  :tooltip-formatter="(value) => `${value}个页面`"
                />
                <p class="parallel-tip">
                  并行数量越多，生成速度越快，但消耗资源也越多
                </p>
              </a-form-item>
              
              <a-form-item>
                <a-button
                  type="primary"
                  size="large"
                  :loading="generating"
                  :disabled="!userMessage.trim()"
                  @click="handleGenerate"
                  block
                >
                  <ThunderboltOutlined />
                  开始生成页面
                </a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
        
        <a-col :span="12">
          <a-card title="生成结果" class="result-card">
            <div v-if="!generateResult && !generating" class="empty-result">
              <a-empty description="请输入需求并点击生成按钮" />
            </div>
            
            <a-spin :spinning="generating" tip="AI正在生成页面，请稍候...">
              <div v-if="generateResult" class="result-content">
                <div class="result-header">
                  <h3>生成成功！</h3>
                  <a-space>
                    <a-button @click="copyResult">
                      <CopyOutlined />
                      复制代码
                    </a-button>
                    <a-button type="primary" @click="downloadResult">
                      <DownloadOutlined />
                      下载文件
                    </a-button>
                  </a-space>
                </div>
                
                <div class="code-preview">
                  <pre><code>{{ generateResult }}</code></pre>
                </div>
              </div>
            </a-spin>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  ThunderboltOutlined,
  CopyOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'
import { preChat } from '@/api/app'
import { generatePages } from '@/api/ai'
import type { App } from '@/types/api'

const route = useRoute()
const router = useRouter()

const currentApp = ref<App | null>(null)
const userMessage = ref('')
const parallelNum = ref(3)
const generating = ref(false)
const generateResult = ref('')

const goBack = () => {
  router.push('/app-market')
}

const handleGenerate = async () => {
  if (!userMessage.value.trim()) {
    message.warning('请输入页面需求描述')
    return
  }
  
  try {
    generating.value = true
    const response = await generatePages({
      userMessage: userMessage.value,
      parallelNum: parallelNum.value
    })
    
    if (response.code === 200) {
      generateResult.value = response.data
      message.success('页面生成成功！')
    } else {
      message.error(response.message || '生成失败')
    }
  } catch (error) {
    console.error('生成页面失败:', error)
    message.error('生成页面失败，请稍后重试')
  } finally {
    generating.value = false
  }
}

const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(generateResult.value)
    message.success('代码已复制到剪贴板')
  } catch (error) {
    message.error('复制失败')
  }
}

const downloadResult = () => {
  const blob = new Blob([generateResult.value], { type: 'text/html' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `generated-page-${Date.now()}.html`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  message.success('文件下载成功')
}

const initPreChat = async () => {
  const appId = route.query.appId as string
  if (appId) {
    try {
      const response = await preChat(Number(appId))
      if (response.code === 200) {
        userMessage.value = response.data || ''
      }
    } catch (error) {
      console.error('获取预聊天内容失败:', error)
    }
  }
  
  // 从路由参数获取应用信息
  if (route.query.app) {
    try {
      currentApp.value = JSON.parse(route.query.app as string)
    } catch (error) {
      console.error('解析应用信息失败:', error)
    }
  }
}

onMounted(() => {
  initPreChat()
})
</script>

<style scoped>
.ai-generate-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
}

.generate-header {
  text-align: center;
  margin-bottom: 32px;
  color: white;
}

.back-btn {
  position: absolute;
  left: 24px;
  top: 24px;
  color: white;
}

.generate-header h1 {
  font-size: 36px;
  margin: 0 0 8px 0;
  color: white;
}

.generate-content {
  max-width: 1400px;
  margin: 0 auto;
}

.input-card,
.result-card {
  height: 600px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.parallel-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.empty-result {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.code-preview {
  flex: 1;
  overflow: auto;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.code-preview pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
}
</style>